package com.ias.agdis_r.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.message.MessageSendActivity;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.SubmittaskmarkRequest;
import com.ias.agdis_r.terminalmanager.restful.task.vo.SubmitTaskMarkRequestVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.ServiceLabelUtil;
import com.ias.agdis_r.util.network.HttpUtil;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by guoxr on 2015/9/14.
 */

public class TaskMonitorAdapter extends BaseAdapter {
    private Context context = null;
    private ArrayList<HashMap<String, Object>> mylist;
    private String tnb, type;
    private String editContent = ""; // 修改服务标注的值
    private SubmittaskmarkRequest submittaskmarkRequest;
    private AlertDialog dialog;
    private int selectItem = -1;

    public TaskMonitorAdapter(Context context, ArrayList<HashMap<String, Object>> mylist, String tnb, String type) {
        this.context = context;
        this.mylist = mylist;
        this.tnb = tnb;
        this.type = type;
    }

    public final class ViewHolder {
        public TextView moniter_item, moniter_content;
        public Button btn_modify;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();
        if (null == convertView) {// 如果加载item布局为null
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.adapter_monitor, null);// 设置加载布局
            holder.btn_modify = (Button) convertView.findViewById(R.id.btn_modify);
            holder.moniter_item = (TextView) convertView.findViewById(R.id.txt_moniter_item);
            holder.moniter_content = (TextView) convertView.findViewById(R.id.txt_moniter_content);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.moniter_item.setText(mylist.get(position).get("MONITOR_ITEM").toString());
        if("X".equals(mylist.get(position).get("MONITOR_CONTENT").toString())){
            holder.moniter_content.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.no_report),null,null,null);
            holder.moniter_content.setCompoundDrawablePadding(10);
            holder.moniter_content.setText("");
        }else{
            holder.moniter_content.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
            holder.moniter_content.setCompoundDrawablePadding(0);
            holder.moniter_content.setText(mylist.get(position).get("MONITOR_CONTENT").toString());
        }

        if (type.equals("BZ")) {
            // 显示标注按钮
            holder.btn_modify.setText(R.string.biaozhu);
            holder.btn_modify.setVisibility(View.VISIBLE);
            // 标注按钮点击事件
            holder.btn_modify.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    showDialog(position);
                }
            });
        }

        if (type.equals("CB")) {
            holder.btn_modify.setText(R.string.cuiban);
            // 设置催办按钮是否隐藏
            ArrayList<HashMap<String, String>> rmd = JavaBeanManager
                    .getInstance().getMSGRemind();
            if (rmd != null) {
                final Task task = DataManager.getInstance().getWorkTask(tnb);
                WriteLog.getInstance().writeLog("TaskMonitorAdapter,tnb:"+tnb);
                if (task != null && task.getTaskInfo() != null && S.isNotEmpty(task.getTaskInfo().getRTP())) {
                    WriteLog.getInstance().writeLog("TaskMonitorAdapter,notNull");
                    for (int n = 0; n < rmd.size(); n++) {
                        HashMap<String, String> nRmd = rmd.get(n);
                        if (nRmd != null) {
                            String pcid = S.valueOf(nRmd.get(MessageModel.PCID));
                            String senm = S.valueOf(nRmd.get(MessageModel.SENM));
                            String rtp = task.getTaskInfo().getRTP();
                            HashMap<String, Object> hashmapM = mylist.get(position);
                            if (pcid.equals(hashmapM.get("MONITOR_TYPE")) && (S.isEmpty(senm) || rtp.equals(senm))) {
                                holder.btn_modify.setVisibility(View.VISIBLE);
                                break;
                            } else {
                                holder.btn_modify.setVisibility(View.INVISIBLE);
                            }
                        } else {
                            WriteLog.getInstance().writeLog("TaskMonitorAdapter,nRmd==null");
                        }
                    }
                    // 催办按钮点击事件
                    holder.btn_modify.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            HashMap<String, Object> hashmapM = mylist.get(position);
//                        HashMap<String, Object> hmRemindViewData = new HashMap<String, Object>();
                        // 传递当前航班的信息
//                        hmRemindViewData.put(MessageModel.strTxtValue[MessageModel.nFLN],
//                                task.getTaskInfo().getFLN());
//                        hmRemindViewData.put(MessageModel.TNB, tnb);
//                        hmRemindViewData.put(MessageModel.strTxtValue[MessageModel.nFKE],
//                                task.getTaskInfo().getFKE());
//                        hmRemindViewData.put(MessageModel.HCC_MONITOR_ITEM,
//                                S.valueOf(hashmapM.get("MONITOR_ITEM")));
                        ArrayList<HashMap<String, String>> rmdList = JavaBeanManager
                                .getInstance().getMSGRemind();
                        if (rmdList == null) {
                            EffectManager.getInstance().ttsPlay(
                                    EffectManager.TTS_TYPE_TASK, context.getString(R.string.noCB), false);
                            return;
                        }
                        List<HashMap<String, String>> selcetRemindList = new ArrayList<HashMap<String, String>>();
                        for (HashMap<String, String> rmdMap : rmdList) {
                            String senm = rmdMap.get(MessageModel.SENM);
                            if (hashmapM.get("MONITOR_TYPE").equals(
                                    rmdMap.get(MessageModel.PCID)) && (S.isEmpty(senm) || task.getTaskInfo().getRTP().equals(senm))) {
                                selcetRemindList.add(rmdMap);
                            }
                        }
                        if (selcetRemindList.size() > 0) {
//                            hmRemindViewData.put(MessageModel.HCC_MONITOR_REMIND_INFO,
//                                    selcetRemindList);
                                //By qibo.yu 启动发送催办短语界面
                                Intent intent = new Intent(context, MessageSendActivity.class);
                                intent.putExtra(MessageSendActivity.EXTRA_TYPE, MessageSendActivity.TYPE_REMIND);
                                intent.putExtra(MessageSendActivity.EXTRA_TNB, tnb);
                                intent.putExtra(MessageSendActivity.EXTRA_FKE, task.getTaskInfo().getFKE());
                                intent.putExtra(MessageSendActivity.EXTRA_FLN, task.getTaskInfo().getFLN());
                                intent.putExtra(MessageSendActivity.EXTRA_RDN, S.valueOf(hashmapM.get("MONITOR_ITEM")));
                                intent.putExtra(MessageSendActivity.EXTRA_PID, hashmapM.get("MONITOR_TYPE").toString());
                                intent.putExtra(MessageModel.RTP, task.getTaskInfo().getRTP());
                                context.startActivity(intent);
                            }
                        }
                    });
                } else {
                    if (task == null){
                        WriteLog.getInstance().writeLog("TaskMonitorAdapter,task==null");
                    }else if (task.getTaskInfo() == null){
                        WriteLog.getInstance().writeLog("TaskMonitorAdapter,task.getTaskInfo==null");
                    }else if (task.getTaskInfo().getRTP() == null){
                        WriteLog.getInstance().writeLog("TaskMonitorAdapter,task.getTaskInfo().getRTP()==null");
                    }
                }
            }
        }
        if (position == selectItem) {
            convertView.setBackgroundColor(Color.CYAN);
        } else {
            convertView.setBackgroundColor(Color.TRANSPARENT);
        }
        return convertView;
    }

    private void showDialog(final int position) {
        AlertDialog.Builder dialogb = new AlertDialog.Builder(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog, null);
        dialogb.setTitle(context.getString(R.string.inputBZ));
        EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.inputBZ), false);
        dialogb.setView(layout);
        final EditText txt_monitor_content = (EditText) layout.findViewById(R.id.edit_content);
        String sMonitorContent = S.valueOf(mylist.get(position).get("MONITOR_CONTENT"));
        txt_monitor_content.setText(sMonitorContent);
        dialogb.setPositiveButton(context.getString(R.string.confirm),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        editContent = txt_monitor_content.getText().toString();
                        if (!checkMonitorContent(editContent)) {
                            return;
                        }
                        sendServiceReport(position);
                        dialog.dismiss();
                    }
                });
        dialogb.setNegativeButton(context.getString(R.string.cancel), null);
        dialog = dialogb.create();
        dialog.show();
    }

    /**
     * 修改项非空，以及包含"'"校验
     *
     * @param content
     * @return
     */
    private boolean checkMonitorContent(String content) {
        if (content.trim().length() == 0) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
                    context.getString(R.string.inputInfo), false);
            return false;
        }
        if (S.isEmpty(content) || content.indexOf("'") > -1) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
                    context.getString(R.string.notNull), false);
            return false;
        } else if (editContent.contains("@") || editContent.contains("#")) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
                    context.getString(R.string.writeError), false);
            return false;
        } else if (editContent.length() > 20) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
                    context.getString(R.string.lessThan21), false);
            return false;
        }
        return true;
    }

    /**
     * 发送上报服务标注消息
     *
     * @param _nSelect
     */
    private void sendServiceReport(int _nSelect) {
        HashMap<String, Object> hashmapM = mylist.get(_nSelect);
        String sMki = S.valueOf(hashmapM.get("MONITOR_TYPE"));
        String sTnb = S.valueOf(tnb);
        initTMRP(sTnb, sMki, editContent);
        HttpUtil.getInstance().sendRequest(submittaskmarkRequest, MessageModel.TMRP, true);
        ServiceLabelUtil.saveReportServiceLabel(sTnb + sMki, editContent);
    }

    private void initTMRP(String tnb, String mki, String cnt) {
        submittaskmarkRequest = new SubmittaskmarkRequest();
        SubmitTaskMarkRequestVO submittaskmarkRequestVO = new SubmitTaskMarkRequestVO();
        submittaskmarkRequestVO.setTNB(tnb);
        submittaskmarkRequestVO.setMKI(mki);
        submittaskmarkRequestVO.setCNT(cnt);
        submittaskmarkRequestVO.setSDT(S.getNowTime());
        submittaskmarkRequest.setSubmittaskmarkRequestVO(submittaskmarkRequestVO);
    }

    public void setSelectItem(int selectItem) {
        this.selectItem = selectItem;
    }

    @Override
    public int getCount() {
        return mylist.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }
}
